<?php

declare(strict_types=1);

namespace app\controller\system\order;

use app\BaseController;
use app\service\factory\ResponseFactory;
use app\service\order\AfterSaleService;
use think\Response;
use Throwable;

class Refund extends BaseController
{
    public function index(AfterSaleService $afterSaleService): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only([
                'keyword',
                'status',
                'order_status',
                'order_refund_status',
                'buyer_org_id',
                'seller_org_id',
                'assist_user_id',
                'buyer_user_id',
                'seller_user_id',
                'start_time',
                'end_time',
            ], 'get');

            $filters = array_filter(
                $filters,
                static fn($value) => $value !== null && $value !== ''
            );

            $paginator = $afterSaleService->paginateWithDetails($filters, $page, $pageSize);
            $list = $afterSaleService->formatCollection($paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, AfterSaleService $afterSaleService): Response
    {
        try {
            $refund = $afterSaleService->getWithDetails($id);
            return json(ResponseFactory::success($afterSaleService->format($refund)));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code >= 600 || $code < 100) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }
}
